using System;
using System.Collections.Generic;
using CMS_Admin.Backend.Api.Entity;
using Microsoft.AspNetCore.Mvc;
using System.Linq;
using CMS_Admin.Backend.Api.ParamModel;
using Newtonsoft.Json;
using CMS_Admin.Backend.Api.Repository;
using CMS_Admin.Backend.Api.Utils;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Authorization;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Authentication;

namespace CMS_Admin.Backend.Controllers
{
    /// <summary>
    /// 客户端
    /// </summary>
    [Authorize]
    [ApiController]
    [Route("client")]
    public class ClientController : ControllerBase
    {

        private IRepository<ArticleClass> _articleClass;
        private readonly IConfiguration _configuration;

        private IRepository<Likes> _likes;
        private IRepository<Articles> _article;
        private IRepository<Users> _users;
        private IRepository<Comments> _comments;
        private IRepository<UserArticles> _userArticles;
        private IRepository<Resource> _resource;


        public ClientController(IConfiguration configuration, IRepository<ArticleClass> articleClass,
                                 IRepository<Likes> likes, IRepository<Articles> article, IRepository<Users> users,
                                 IRepository<Comments> comments, IRepository<UserArticles> userArticles,
                                 IRepository<Resource> resource)
        {

            _articleClass = articleClass;
            _configuration = configuration;
            _likes = likes;
            _article = article;
            _users = users;
            _comments = comments;
            _userArticles = userArticles;
            _resource = resource;



        }


        /// <summary>
        /// 查找文章栏目
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpGet]
        public dynamic Get()
        {

            var articleClass = _articleClass.Table.OrderByDescending(art => art.Id).Where(a => a.IsDeleted == false);

            var res = new
            {
                Code = 200,
                Data = articleClass,

                Msg = "获取栏目列表成功^_^"
            };
            return res;
        }




        /// <summary>
        /// 点赞
        /// </summary>
        /// <param name="id"></param>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPut("/liked/{id}")]
        public dynamic Put(int id, NewLike model)
        {



            var claims = base.HttpContext.AuthenticateAsync().Result
           .Principal.Claims.FirstOrDefault().Subject.Claims;


            var userid = claims.FirstOrDefault(c => c.Type == "id")?.Value;
            var likes = _likes.Table.Where(l => l.UsersId == int.Parse(userid)&&l.ArticlesId==id).FirstOrDefault();

            if(userid==null){
                var res = new
            {
                Code = 200,
                Data = "",

                Msg = "用户未登录！"
            };
            return res;
            }
            if (likes != null)
            {

                likes.Liked = model.Liked;


                likes.UpdatedTime = DateTime.Now;


                _likes.Update(likes);


                return JsonHelper.Serialize(new
                {
                    Code = 200,
                    Data = likes,
                    Msg = "点赞成功"
                });
            }
            else
            {

                var uid = userid;
                var aid = id;
                var liked = model.Liked;

                var like = new Likes
                {
                    Liked = liked,
                    Articles = _article.Table.Single(r => r.Id == aid),
                    Users = _users.Table.Single(u => u.Id == int.Parse(uid))
                };
                _likes.Insert(like);

                return JsonHelper.Serialize(new
                {
                    Code = 1004,
                    Data = "",
                    Msg = "插入点赞信息成功"
                });
            }
        }




        /// <summary>
        /// 根据栏目获取文章列表
        /// </summary>
        /// <param name="pager"></param>
        /// <param name="articleClassName"></param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpGet("/articleclassify")]
        public dynamic Get([FromQuery] Pager pager, string articleClassName)
        {
            var pageIndex = pager.PageIndex;
            var pageSize = pager.PageSize;

            var comment = from comments in _comments.Table

                          group comments by new { comments.ArticlesId }
                           into g
                          select new { ArticlesId = g.Key.ArticlesId, Count = g.Count() };


            var like = from likes in _likes.Table
                       where likes.Liked == true
                       group likes by new { likes.ArticlesId }

                       into l
                       select new { ArticlesId = l.Key.ArticlesId, Count = l.Count() };


            System.Console.WriteLine(comment);

            var article = from articles in _article.Table
                          join artcleclasses in _articleClass.Table on articles.ArticleClassId equals artcleclasses.Id
                          join userArticles in _userArticles.Table on articles.Id equals userArticles.ArticlesId
                          join user in _users.Table on userArticles.UserId equals user.Id
                          join resoure in _resource.Table on articles.ResourceId equals resoure.Id

                          orderby articles.Id
                          where articles.IsDeleted == false && artcleclasses.ArticleClassName == articleClassName
                          select new
                          {
                              Id = articles.Id,
                              Username = user.Username,
                              articleTitle = articles.ArticleTitle,
                              Content = articles.Content,
                              redaNumber = articles.ReadNumber,
                              articlesClsssName = artcleclasses.ArticleClassName,
                              CreatedTime = articles.CreatedTime,
                              ResoutceName = resoure.ResoutceName
                          };


            // var c = comment.Count();
            // 对获得的记录分页
            var u = article.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();

            // // 返回的数据里，带有数据和分页信息
            var res = new
            {
                Code = 200,
                Data = new
                {
                    Data = u,
                    comment = comment.ToList(),
                    like = like.ToList(),
                    Pager = new
                    {
                        pageIndex,
                        pageSize,
                        rowsTotal = article.Count(),
                    }
                },
                Msg = "获取文章列表成功^_^"
            };
            return JsonHelper.Serialize(res);
        }

        /// <summary>
        /// 获取热点
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpGet("/hotspot")]

        public dynamic GetHotspot()
        {

            var hot = _article.Table.OrderByDescending(h => h.ReadNumber).Where(i => i.Id <= 5);


            var res = new
            {
                Code = 200,
                Data = hot,

                Msg = "获取热点成功！"
            };
            return res;

        }

        /// <summary>
        /// 评论热榜
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpGet("/Comment")]

        public dynamic GetComment()
        {


            var comment = from comments in _comments.Table
                          join article in _article.Table on comments.ArticlesId equals article.Id
                          group comments by new { comments.ArticlesId, article.ArticleTitle, article.Content }
                          into g
                          select new
                          {
                              Id = g.Key,
                              ArticlesId = g.Key.ArticlesId,
                              Count = g.Count(),
                              ArticleTitle = g.Key.ArticleTitle,
                              Content = g.Key.Content
                          };

            var b = comment.OrderByDescending(c =>c.Count).Take(5);

    
            var res = new
            {
                Code = 200,
                Data = new
                {
                    b
                  

                },

                Msg = "获取热点成功！"
            };
            return res;
        }




        /// <summary>
        /// 点赞热榜
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpGet("/liked")]

        public dynamic GetLiked()
        {



            var like = from likes in _likes.Table
                       join article in _article.Table on likes.ArticlesId equals article.Id
                       where likes.Liked == true
                       group likes by new { likes.ArticlesId, article.ArticleTitle, article.Content }

                       into l
                       select new
                       {
                           ArticlesId = l.Key.ArticlesId,
                           Count = l.Count(),
                           ArticleTitle = l.Key.ArticleTitle,
                           Content = l.Key.Content
                       };
                       var s =like.Take(5).OrderByDescending(c => c.Content);
            var res = new
            {
                Code = 200,
                Data = new
                {
                    
                    like

                },

                Msg = "获取热点成功！"
            };
            return res;
        }

        /// <summary>
        /// 添加阅读数量
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPut("/reader/{id}")]
        [AllowAnonymous]
        public dynamic PutReader(int id)
        {

            var r = _article.GetById(id);
            r.ReadNumber = r.ReadNumber + 1;

            _article.Update(r);
            var res = new
            {
                Code = 200,
                Data = r,

                Msg = "阅读数添加成功！"
            };
            return res;


        }







    }
}